package com.wanban.download.downloadutils

import android.util.Log
import com.tencent.rtmp.TXLiveBase
import com.tencent.rtmp.TXPlayerGlobalSetting
import com.tencent.rtmp.downloader.ITXVodDownloadListener
import com.tencent.rtmp.downloader.TXVodDownloadManager
import com.tencent.rtmp.downloader.TXVodDownloadMediaInfo
import com.wanban.download.BuildConfig
import com.wanban.download.base.BaseDownloadUtils
import com.wanban.download.db.DownloadEntity
import com.wanban.download.listener.OnFileDownloadListener
import com.wanban.download.utils.DownloadConstants
import com.wanban.download.utils.PathUtils
import com.wanban.download.utils.RxJavaUtils
import io.reactivex.Flowable
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit

/**
 * 下载器
 */
class TXDownloadUtils: BaseDownloadUtils, ITXVodDownloadListener {

    companion object {
        const val USERNAME = "default"
        const val PREFERRED_RESOLUTION = 1920 * 1080L

        fun deleteTask(url: String){
            val txDownloader = TXVodDownloadManager.getInstance()
            val mediaInfo = txDownloader.getDownloadMediaInfo(url, PREFERRED_RESOLUTION, USERNAME)
            if (mediaInfo != null) {
                txDownloader.deleteDownloadMediaInfo(mediaInfo)
            }
        }
    }

    private var tempContentLength = 0L
    private var listener: OnFileDownloadListener? = null
    private var mediaInfo: TXVodDownloadMediaInfo? = null

    // 腾讯下载器
    private val downloader by lazy {
        val instance = TXVodDownloadManager.getInstance()
        instance.setListener(this)
        return@lazy instance
    }

    init {
        // 若您服务全球用户， 配置 SDK 接入环境为全球接入环境
        try {
            TXLiveBase.setGlobalEnv("GDPR")
            RxJavaUtils.doAsync {
                val sdcardDir = PathUtils.getTXRootPath()
                TXPlayerGlobalSetting.setCacheFolderPath("$sdcardDir/cache")
            }
        } catch (e: UnsatisfiedLinkError) {
            e.printStackTrace()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    // 启动下载
    override fun startDownload(task: DownloadEntity, listener: OnFileDownloadListener) {
        task.startTaskTime = System.currentTimeMillis()
        tempContentLength = task.tempContentLength
        // 腾讯下载
        if (task.header != null) {
            downloader.setHeaders(task.header)
        }
        this.listener = listener
        mediaInfo = downloader.startDownloadUrl(task.url, PREFERRED_RESOLUTION, USERNAME)
    }

    // 暂停下载
    override fun stopDownload(){
        if (mediaInfo == null) return
        // 停止解析或者下载
        downloader.stopDownload(mediaInfo)
    }

    // 删除下载
    override fun deleteDownloadFile(task: DownloadEntity) {
        if (mediaInfo == null) return
        downloader.stopDownload(mediaInfo)
        Flowable.timer(500, TimeUnit.MILLISECONDS)
            .subscribeOn(Schedulers.io())
            .subscribe({
                downloader.deleteDownloadMediaInfo(mediaInfo)
                PathUtils.deleteTaskFiles(task)
            }, {
                it?.printStackTrace()
            }).isDisposed
    }


    override fun onDownloadStart(p0: TXVodDownloadMediaInfo?) {
        if (p0 == null) return
        listener?.onStart(p0.url)
    }

    override fun onDownloadProgress(p0: TXVodDownloadMediaInfo?) {
        if (p0 == null) return
        val contentLength = (tempContentLength * p0.progress).toLong()
        if (BuildConfig.DEBUG) {
            val speedStr = DownloadConstants.byte2FitMemorySize(p0.speed * 1024L, 2)
            val currentLengthStr = DownloadConstants.byte2FitMemorySize(contentLength, 2)
            Log.d("TXDownload", "downloading -> $speedStr - $currentLengthStr, ${p0.progress * 100}% ")
        }
        listener?.onProgress(p0.url, p0.speed * 1024L, contentLength, p0.progress * 100)
    }

    override fun onDownloadStop(p0: TXVodDownloadMediaInfo?) {

    }

    override fun onDownloadFinish(p0: TXVodDownloadMediaInfo?) {
        if (p0 == null) return
        listener?.onComplete(p0.url, p0.size, p0.playPath)
    }

    override fun onDownloadError(p0: TXVodDownloadMediaInfo?, p1: Int, p2: String?) {
        if (p0 == null) return
        val errorMsg = when(p1) {
            TXVodDownloadManager.DOWNLOAD_AUTH_FAILED -> "下载器初始化失败！"
            TXVodDownloadManager.DOWNLOAD_NO_FILE -> "无此清晰度文件。"
            TXVodDownloadManager.DOWNLOAD_FORMAT_ERROR -> "下载文件格式不支持。"
            TXVodDownloadManager.DOWNLOAD_DISCONNECT -> "网络断开，建议检查网络是否正常。"
            TXVodDownloadManager.DOWNLOAD_HLS_KEY_ERROR -> "获取 HLS 解密 Key 失败。"
            TXVodDownloadManager.DOWNLOAD_PATH_ERROR -> DownloadConstants.ERROR_DOWNLOAD_FILE_CREATE
            TXVodDownloadManager.DOWNLOAD_403FORBIDDEN -> "请求下载时，鉴权信息不通过！"
            else -> "下载成功"
        }
        listener?.onError(p0.url, errorMsg)
    }

    override fun hlsKeyVerify(p0: TXVodDownloadMediaInfo?, p1: String?, p2: ByteArray?): Int {
        return 0
    }
}